package com.it.day7;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * ClassName: AtomicIntegerFieldUpdaterDemo
 * Description: 对象的基本类型属性修改原子类
 *
 * @Author: csx
 * @Create: 2025/5/13 - 17:15
 * @version: v1.0
 */
public class AtomicIntegerFieldUpdaterDemo {
    public static void main(String[] args) {
        BankAccount bankAccount = new BankAccount();

        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                bankAccount.transferMoney();
            }, String.valueOf(i)).start();
        }

        try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println(bankAccount.fieldUpdater.get(bankAccount));
    }
}

class BankAccount{
    private volatile int money = 0;

    AtomicIntegerFieldUpdater<BankAccount> fieldUpdater =
            AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "money");

    public void transferMoney(){
        fieldUpdater.incrementAndGet(this); //自增
    }
}
















